/*
 * main.c
 *
 *  Created on: 2010-3-11
 *      Author: abc
 */
#include <signal.h>
#include "clientInfoList.h"
//#define MAXLEN 1024
#define   MAXBUF   256

pclientinfo clientlink;
int   port=5000;
char  *  multicast_addr= "224.0.1.1 ";

extern void* handleaccept(void* p);
extern void * multiThread(void* p);


void handleSrvMsg(){

}

void handlesignal()
{
	int choose;
	char name[10];
	while(1)
	{
        	printf("1.T除指定客户端，2.关闭服务器,3.显示在线客户端,4发送服务器消息\n");
        	scanf("%d",&choose);
        	while(choose < 1 || choose > 4)
        	{
			printf("请输入上面提示的选项:\n");
			scanf("%d",&choose);
        	}

        	gets(name);
        	if(choose == 1)
        	{
			printf("请输入你踢出去的客户端名字:\n");
			gets(name);
			if(strcmp(name,"") == 0) continue;
			DisplayList(clientlink);
			pclientinfo L,s;
			L = clientlink;
			L=L->next;
			s = L;
			while((strcmp(L->name,name) != 0) && L->next != NULL)
			{
				s = L;
				L = L->next;
			}
			//printf("1%s\n",L->data.name);
			if(L->next == NULL && (strcmp(L->name,name) != 0))
			{
				printf("该客户端不存在\n");

			}
			else
			{
				close(L->sockfd);
				pthread_cancel(L->pid);
				s->next = L->next;
				free(L);
			}
			printf("3\n");


        	}
        	else if(choose == 2)
        	{
		/*
			LinkList L,s;
			L = clientlink->next;
			while(L != NULL)
			{
				s = L->next;
				close(L->data.decr);
				free(L);
				L = s;
			}

			free(clientlink);
		*/	return;
        	}
        	else if(choose == 3)
        	{
			DisplayList(clientlink);

        	}
        	else if(choose == 4){
        		handleSrvMsg();
        	}
	}
}

int main(int argc,char* argv[]){
	    struct sockaddr_in server_addr,client_addr;
		int sockfd,connectfd,nread;
		pthread_t pid;
		char buf[MAXLEN];
		char str[MAXLEN];


		//if(argc != 2)
		//{
		//	printf("请输入端口\n");
		//	exit(1);
		//}
		printf("please enter the port number!\n");
		//gets(str);
		strcpy(str,"12345");
		port = atoi(str);
	    if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
	    {
				printf("创建socket失败\n");
				exit(1);
	    }
	    clientlink = CreateLinkList();
	    clientlink->sockfd = sockfd;

	    bzero(&server_addr,sizeof(struct sockaddr_in));
	    server_addr.sin_family = AF_INET;
	    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	    server_addr.sin_port = htons(port);
		if(bind(sockfd,(struct sockaddr *)&server_addr,sizeof(struct sockaddr)) == -1)
	    {
			printf("绑定端口失败,端口可能被占用\n");
			exit(2);
		}
	    if(listen(sockfd,20) == -1)
	    {
				printf("监听端口失败\n");
				exit(3);
	    }

	    printf("正在port:%d监听中...\n",port);
	    pthread_create(&pid,NULL,(void *)handleaccept,(void *)&sockfd);
	    pthread_create(&pid,NULL,(void *)multiThread,(void *)&sockfd);
	    handlesignal();
	    return 0;
}
